package com.work.work.util;

        import io.jsonwebtoken.*;
        import io.jsonwebtoken.security.Keys;
        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.stereotype.Component;

        import javax.crypto.SecretKey;
        import java.nio.charset.StandardCharsets;
        import java.util.Date;
        import java.util.HashMap;
        import java.util.Map;

        @Component
        public class JwtUtil {
            @Value("${jwt.secret}")
            private String secret;

            @Value("${jwt.expiration}")
            private Long expiration;

            // 生成密钥
            private SecretKey getSigningKey() {
                byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
                return Keys.hmacShaKeyFor(keyBytes);
            }

            public String createToken(Integer userId, String username, Integer roleId) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("userId", userId);
                claims.put("username", username);
                claims.put("roleId", roleId);

                Date now = new Date();
                Date expirationDate = new Date(now.getTime() + expiration);

                return Jwts.builder()
                        .setClaims(claims)
                        .setIssuedAt(now)
                        .setExpiration(expirationDate)
                        .signWith(getSigningKey())
                        .compact();
            }

            public Claims parseToken(String token) {
                return Jwts.parserBuilder()
                        .setSigningKey(getSigningKey())
                        .build()
                        .parseClaimsJws(token)
                        .getBody();
            }

            public Integer getUserId(String token) {
                Claims claims = parseToken(token);
                return claims.get("userId", Integer.class);
            }

            public String getUsername(String token) {
                Claims claims = parseToken(token);
                return claims.get("username", String.class);
            }

            public Integer getRoleId(String token) {
                Claims claims = parseToken(token);
                return claims.get("roleId", Integer.class);
            }

            public boolean validateToken(String token) {
                try {
                    Jwts.parserBuilder()
                            .setSigningKey(getSigningKey())
                            .build()
                            .parseClaimsJws(token);
                    return true;
                } catch (JwtException e) {
                    return false;
                }
            }
        }